package com.sc.adminspringboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sc.adminspringboot.dao.*;
import com.sc.adminspringboot.dto.TagInfo;
import com.sc.adminspringboot.pojo.PostTags;
import com.sc.adminspringboot.pojo.Tags;
import com.sc.adminspringboot.pojo.UserPreferences;
import com.sc.adminspringboot.service.ITagsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Carson
 * @since 2025-09-22 04:46:00
 */
@Service
public class TagsServiceImpl extends ServiceImpl<ITagsDao, Tags> implements ITagsService {
    @Autowired
    private ITagsDao tagMapper;

    @Autowired
    private IPostTagsDao postTagsMapper;

    @Autowired
    private IUserPreferencesDao userPreferencesMapper;

    @Autowired
    private IPostsDao postMapper;

    @Autowired
    private IUsersDao userMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTagAndCreateAssociation(TagInfo tagInfo) {
        // 1. 检查标签名称是否已存在
        QueryWrapper<Tags> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq("tag_name", tagInfo.getTagName());
        if (tagMapper.selectCount(tagQueryWrapper) > 0) {
            throw new RuntimeException("标签名称已存在");
        }
        // 1. 插入新标签并获取生成的 tagId
        Tags tag = new Tags();
        tag.setTagName(tagInfo.getTagName());
        tag.setType(tagInfo.getType());
        tagMapper.insert(tag);

        Integer tagId = tag.getId(); // 假设 MyBatis-Plus 会自动填充

        // 2. 根据类型创建关联
        if (tagInfo.getType() == 1) { // 假设1表示关联帖子
            // 验证postId是否存在
            if (postMapper.selectById(tagInfo.getRelatedId()) == null) {
                throw new RuntimeException("关联的帖子不存在");
            }
            PostTags postTags = new PostTags();
            postTags.setPostId(tagInfo.getRelatedId());
            postTags.setTagId(tagId);
            postTags.setClicktime(tagInfo.getClickTime());
            try {
                postTagsMapper.insert(postTags);
            } catch (Exception e) {
                // 处理唯一性约束冲突（如 post_id + tag_id 联合唯一索引）
                if (e.getMessage().contains("Duplicate entry") || e.getMessage().contains("UNIQUE constraint failed")) {
                    throw new RuntimeException("该帖子已关联此标签");
                }
                throw e; // 其他异常继续抛出
            }
        } else if (tagInfo.getType() == 2) { // 假设2表示关联用户
            // 验证userId是否存在
            if (userMapper.selectById(tagInfo.getRelatedId()) == null) {
                throw new RuntimeException("关联的用户不存在");
            }
            UserPreferences userPreferences = new UserPreferences();
            userPreferences.setUserId(tagInfo.getRelatedId());
            userPreferences.setTagId(tagId);
            userPreferences.setClickTime(tagInfo.getClickTime());
            try {
                userPreferencesMapper.insert(userPreferences);
            } catch (Exception e) {
                // 处理唯一性约束冲突（如 user_id + tag_id 联合唯一索引）
                if (e.getMessage().contains("Duplicate entry") || e.getMessage().contains("UNIQUE constraint failed")) {
                    throw new RuntimeException("该用户已关联此标签");
                }
                throw e; // 其他异常继续抛出
            }
        }
    }

    @Override
    public IPage<TagInfo> preferTags(IPage<TagInfo> pageData) {
        return tagMapper.selectPreferTagsWithPage(pageData);
    }

    @Override
    public IPage<TagInfo> postTags(IPage<TagInfo> pageData) {
        return tagMapper.selectPostTagsWithPage(pageData);
    }
}
